from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, RetrieveAPIView
from .models import CourseCategory, Course, CourseChapter
from .serializers import CourseCategoryModelSerializer, CourseModelSerializer, CourseRetrieveModelSerializer, \
    CourseChapterModelSerializer
from .paginations import CustomPageNumberPagination

class CourseCategoryListAPIView(ListAPIView):
    queryset = CourseCategory.objects.filter(is_show=True, is_deleted=False).order_by("orders","-id")
    serializer_class = CourseCategoryModelSerializer


class CourseListAPIView(ListAPIView):
    queryset = Course.objects.filter(is_deleted=False, is_show=True).order_by("orders", "-id")
    serializer_class = CourseModelSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filter_fields = ('course_category', )  # 过滤
    ordering_fields= ('id', 'students', 'price')   # 排序
    pagination_class = CustomPageNumberPagination   #  指定分页器

class CourseRetrieveAPIView(RetrieveAPIView):
    queryset = Course.objects.filter(is_show=True, is_deleted=False).order_by("orders", "-id")
    serializer_class = CourseRetrieveModelSerializer


# 课程章节信息
class CourseChapterListAPIView(ListAPIView):
    queryset = CourseChapter.objects.filter(is_show=True, is_deleted=False).order_by("orders", "-id")
    serializer_class = CourseChapterModelSerializer
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']

# 保利威视频
from luffyapi.libs.polyv import PolyvPlayer
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django.conf import settings
from rest_framework.response import Response

class PolyvAPIView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        """获取视频播放的token"""
        userId = settings.POLYV_CONFIG["userId"]
        secretKey = settings.POLYV_CONFIG["secretKey"]
        tokenUrl = settings.POLYV_CONFIG["tokenUrl"]
        polyv = PolyvPlayer(userId, secretKey, tokenUrl)
        vid = request.query_params.get("vid")
        user_ip = request.META.get("REMOTE_ADDR")  # 用户的ip
        user_id = request.user.id  # 用户ID
        user_name = request.user.username
        result = polyv.get_video_token(vid, user_ip, user_id, user_name)
        return Response(result.get("token"))
